// stores/logSocket.js
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useLogSocketStore = defineStore('logSocket', () => {
  const socket = ref(null)
  const logs = ref([])

  const connect = () => {
    if (socket.value) return
    socket.value = new WebSocket('ws://localhost:8080/ws/logs')

    socket.value.onerror = (error) => {
      console.error('WebSocket error:', error)
    }

    socket.value.onmessage = (event) => {
      logs.value.push({ log: event.data })
      if (logs.value.length > 5000) logs.value.shift()
    }

    socket.value.onclose = () => {
      console.warn('WebSocket closed, attempting reconnect...')
      console.error()
      setTimeout(connect, 3000)
    }
  }

  const disconnect = () => {
    socket.value?.close()
    socket.value = null
  }

  return { socket, logs, connect, disconnect }
})
